﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using BEGDC.Utility.Castle;
using BEGDC.Utility.ExceptionManagement;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.BL.UserManagement;
using BEGDC.CC.BL.Common;
using BEGDC.CC.Entity;
using BEGDC.CC.Web.UserControls;
using NetBpm.Util.Client;
using NetBpm.Workflow.Execution;
using NetBpm.Workflow.Execution.EComp;


namespace BEGDC.CC.Web
{
    /// <summary>
    /// Summary description for main.
    /// </summary>
    public class MySearch : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        private int _SearchID
        {
            get
            {
                if (Session["_SearchID"] == null) return 0;

                return Convert.ToInt32(Session["_SearchID"]);
            }
            set { Session["_SearchID"] = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        private string _SearchType
        {
            get
            {
                if (Session["SearchType"] == null) return "CR";

                return (string)Session["SearchType"];
            }
            set { Session["SearchType"] = value; }
        }

        private System.Collections.Hashtable _SearchFields
        {
            get
            {
                if (ViewState["SearchFields"] == null) return null;

                else return (System.Collections.Hashtable)ViewState["SearchFields"];
            }
            set
            {
                ViewState["SearchFields"] = value;
            }
        }

        protected System.Web.UI.WebControls.Button btnEdit;
        protected System.Web.UI.WebControls.Button btnDelete;
        protected System.Web.UI.WebControls.Button btnExport;
        //protected System.Web.UI.WebControls.ImageButton btnApprove;
        //protected System.Web.UI.WebControls.ImageButton btnReject;
        protected System.Web.UI.WebControls.ImageButton btnPageFirst;
        protected System.Web.UI.WebControls.ImageButton btnPagePrev;
        protected System.Web.UI.WebControls.ImageButton btnPageNext;
        protected System.Web.UI.WebControls.ImageButton btnPageLast;
        protected System.Web.UI.WebControls.Label lblRecordCount;
        protected System.Web.UI.WebControls.Label lblPageCount;
        protected System.Web.UI.WebControls.Label lblCurrentPageIndex;
        protected System.Web.UI.WebControls.DataGrid dgTaskList;
        protected System.Web.UI.WebControls.TextBox txtPage;
        protected System.Web.UI.WebControls.Label lblSearchName;
        protected System.Web.UI.WebControls.Label lblDescription;

        protected System.Web.UI.WebControls.ImageButton btnGotoPage;

        private void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                // Put user code to initialize the page here
                if (!Page.IsPostBack)
                {
                    this._SearchID = Convert.ToInt32(Page.Request.QueryString["searchid"]);

                    BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch iquery = AppContainer.Instance[ServiceConst.SearchService] as BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch;

                    BEGDC.CC.Entity.AdvancedSearch search = iquery.GetAdvancedSearch(_SearchID);

                    this._SearchType = search.SearchType;

                    this.GetSearchFields();

                    //this.btnEdit.Attributes.Add("onclick","javascript:showEditForm('../workflow/advancedsearch.aspx?type=" + this._SearchType + "&id=" + this._SearchID + "');");

                    this.BindData(1);

                    this.btnDelete.Attributes.Add("onclick", "return confirm('Are you sure to delete this advanced search?')");

                }

            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }

        private string SearchSQL
        {
            get
            {
                if (ViewState["SearchSQL"] != null) return (string)ViewState["SearchSQL"];
                else
                    return string.Empty;
            }
            set
            {
                ViewState["SearchSQL"] = value;
            }
        }

        private void BindData(int pageIndex)
        {
            BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch iquery = AppContainer.Instance[ServiceConst.SearchService] as BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch;

            if (this.SearchSQL == string.Empty)
            {
                string searchID = Page.Request.QueryString["searchid"];

                BEGDC.CC.Entity.AdvancedSearch search = iquery.GetAdvancedSearch(Convert.ToInt32(searchID));

                if (search.Employee.Id != ((BEGDC.CC.BL.Workflow.CCIdentity)Page.User.Identity).UserInfo.Id)
                {
                    this.btnDelete.Visible = false;
                    this.btnEdit.Visible = false;
                    this.btnExport.Visible = false;
                    return;
                }
                this.lblSearchName.Text = search.SearchName;
                this.lblDescription.Text = search.Description;

                this.SearchSQL = search.SearchSQL;
            }

            System.Data.DataTable dtSearchs = iquery.QueryList(this.SearchSQL);

            int count = dtSearchs.Rows.Count;

            this.CreateGridColumn(dtSearchs);

            this.dgTaskList.DataSource = dtSearchs;
            this.dgTaskList.DataBind();

            SetPageCount(count, pageIndex);


        }

        public void CreateGridColumn(System.Data.DataTable dtSearchs)
        {
            int i = 0;
            if (this._SearchType != "AP")
            {
                System.Web.UI.WebControls.BoundColumn newCol = new BoundColumn();

                newCol.DataField = "appid";
                newCol.ReadOnly = true;
                newCol.Visible = false;

                this.dgTaskList.Columns.AddAt(0, newCol);

                newCol = new BoundColumn();

                newCol.DataField = "flowid";
                newCol.ReadOnly = true;
                newCol.Visible = false;

                this.dgTaskList.Columns.AddAt(1, newCol);

                i = 2;
            }
            else
            {
                System.Web.UI.WebControls.BoundColumn newCol = new BoundColumn();

                newCol.DataField = "apid";
                newCol.ReadOnly = true;
                newCol.Visible = false;

                this.dgTaskList.Columns.AddAt(0, newCol);

                newCol = new BoundColumn();

                newCol.DataField = "meetingid";
                newCol.ReadOnly = true;
                newCol.Visible = false;

                this.dgTaskList.Columns.AddAt(1, newCol);

                i = 2;
            }

            foreach (System.Data.DataColumn col in dtSearchs.Columns)
            {
                if (col.ColumnName.ToLower() == "appid" || col.ColumnName.ToLower() == "flowid" || col.ColumnName.ToLower() == "currentactivestepname" || col.ColumnName.ToLower() == "type" || col.ColumnName.ToLower() == "apid" || col.ColumnName.ToLower() == "meetingid")
                    continue;

                System.Web.UI.WebControls.BoundColumn newCol = new BoundColumn();
                newCol.HeaderText = this.GetCaption(col.ColumnName);
                newCol.DataField = col.ColumnName;
                newCol.ReadOnly = true;
                newCol.DataFormatString = GetDataFormatString(col.ColumnName);

                newCol.Visible = true;


                this.dgTaskList.Columns.AddAt(i, newCol);
                i++;
            }

        }

        private string GetDataFormatString(string fieldname)
        {
            foreach (SearchField field in this._SearchFields.Values)
            {
                if (field._name.ToLower() == fieldname.ToLower())
                    if (field._datatype == "Date")
                        return "{0:M/d/yyyy}";
            }
            return string.Empty;
        }



        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.btnPageFirst.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageFirst_Click);
            this.btnPagePrev.Click += new System.Web.UI.ImageClickEventHandler(this.btnPagePrev_Click);
            this.btnPageNext.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageNext_Click);
            this.btnPageLast.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageLast_Click);
            this.btnGotoPage.Click += new System.Web.UI.ImageClickEventHandler(this.btnGotoPage_Click);

            this.btnExport.Click += new EventHandler(btnExport_Click);
            this.btnEdit.Click += new EventHandler(btnEdit_Click);
            this.btnDelete.Click += new EventHandler(btnDelete_Click);
            this.dgTaskList.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgTaskList_ItemDataBound);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        #region ---------- paging events ----------------
        private void btnPageFirst_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.dgTaskList.CurrentPageIndex = 0;
            this.BindData(1);
        }

        private void btnPagePrev_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (_CurrentPageIndex == 1) return;
            this.dgTaskList.CurrentPageIndex = _CurrentPageIndex - 2;
            this.BindData(_CurrentPageIndex - 1);
        }

        private void btnPageNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (_CurrentPageIndex == _PageCount) return;
            this.dgTaskList.CurrentPageIndex = _CurrentPageIndex;
            this.BindData(_CurrentPageIndex + 1);
        }

        private void btnPageLast_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            this.dgTaskList.CurrentPageIndex = _PageCount - 1;
            this.BindData(_PageCount);
        }

        private void btnGotoPage_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            if (this.txtPage.Text == string.Empty)
            {
                this.txtPage.Text = "1";
            }
            int gotopage = 1;
            try
            {
                gotopage = Convert.ToInt32(this.txtPage.Text);
            }
            catch { }
            int currentpage = 0;

            if (gotopage >= _PageCount)
            {
                gotopage = _PageCount;
                currentpage = gotopage - 1;
                if (currentpage < 0) currentpage = 0;
            }
            else if (gotopage <= 0)
            {
                gotopage = 1;
            }
            else
            {
                currentpage = gotopage - 1;
            }

            this.dgTaskList.CurrentPageIndex = currentpage;

            this.BindData(gotopage);

            this.txtPage.Text = string.Empty;
        }

        #endregion

        #region page navigation
        private int _PageCount
        {
            get
            {
                if (ViewState["PageCount"] != null) return (int)ViewState["PageCount"];
                else
                    return 0;
            }
            set
            {
                ViewState["PageCount"] = value;
            }
        }
        private int _CurrentPageIndex
        {
            get
            {
                if (ViewState["CurrentPageIndex"] != null) return (int)ViewState["CurrentPageIndex"];
                else
                    return 0;
            }
            set
            {
                ViewState["CurrentPageIndex"] = value;
            }
        }
        private int _RowCount
        {
            get
            {
                if (ViewState["RowCount"] != null) return (int)ViewState["RowCount"];
                else
                    return 0;
            }
            set
            {
                ViewState["RowCount"] = value;
            }
        }
        private void SetPageNavi(int newPage)
        {
            if (newPage <= 1)
            {
                this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_first_inact.gif";
                this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_pre_inact.gif";
                this.btnPageFirst.Attributes["disabled"] = "true";
                this.btnPagePrev.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_first.gif";
                this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_pre.gif";
                this.btnPageFirst.Attributes.Remove("disabled");
                this.btnPagePrev.Attributes.Remove("disabled");
            }

            if (newPage >= _PageCount)
            {
                this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_next_inact.gif";
                this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_last_inact.gif";
                this.btnPageNext.Attributes["disabled"] = "true";
                this.btnPageLast.Attributes["disabled"] = "true";
            }
            else
            {
                this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_next.gif";
                this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path + "/images/pg_last.gif";
                this.btnPageNext.Attributes.Remove("disabled");
                this.btnPageLast.Attributes.Remove("disabled");
            }

            this.lblCurrentPageIndex.Text = newPage.ToString();
            this.lblPageCount.Text = _PageCount.ToString();
            this.lblRecordCount.Text = _RowCount.ToString();

        }

        private void SetPageCount(int count, int pageIndex)
        {
            if (count > 0)
            {
                _RowCount = count;
                _PageCount = count / this.dgTaskList.PageSize;
                if (count % this.dgTaskList.PageSize > 0) _PageCount++;

                _CurrentPageIndex = pageIndex;
                SetPageNavi(pageIndex);
            }
            else
            {
                _RowCount = count;
                _PageCount = count;
                _CurrentPageIndex = 0;
                SetPageNavi(0);
            }
        }

        #endregion

        void btnDelete_Click(object sender, EventArgs e)
        {
            BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch iquery = AppContainer.Instance[ServiceConst.SearchService] as BEGDC.CC.BL.AdvancedSearch.IAdvancedSearch;
            iquery.DeleteSearchById(this._SearchID);

            Page.RegisterClientScriptBlock("", "<script>window.parent.location.href='../default.aspx'</script>");
        }

        void btnEdit_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect("../workflow/advancedsearch.aspx?type=" + this._SearchType + "&id=" + this._SearchID);
        }

        void btnExport_Click(object sender, EventArgs e)
        {
            this.dgTaskList.AllowPaging = false;
            this.BindData(1);

            BEGDC.CC.Web.Control.ExportDataGridToExcel.Export(Page, dgTaskList, "MySearch.xls");
        }

        private void GetSearchFields()
        {
            string filename = this.Request.PhysicalApplicationPath + "\\advancesearch.xml";
            if (System.IO.File.Exists(filename))
            {
                System.IO.TextReader tr = System.IO.File.OpenText(filename);
                string xml = tr.ReadToEnd();

                tr.Close();

                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.LoadXml(xml);

                System.Collections.Hashtable htFields = new Hashtable();

                foreach (System.Xml.XmlNode element in xmlDoc["advanceSearch"].ChildNodes)
                {
                    if (element.Attributes["name"].Value == this._SearchType)
                    {
                        foreach (System.Xml.XmlNode elementField in element.ChildNodes)
                        {
                            SearchField field = new SearchField();
                            field._name = elementField.Attributes["name"].Value;
                            field._description = elementField.Attributes["description"].Value;
                            field._isdefault = Convert.ToBoolean(elementField.Attributes["isdefault"].Value);
                            field._issearch = Convert.ToBoolean(elementField.Attributes["issearch"].Value);
                            field._datatype = elementField.Attributes["datatype"].Value; ;
                            htFields.Add(field._name, field);
                        }
                    }
                }
                this._SearchFields = htFields;

            }

        }


        private string GetCaption(string fieldname)
        {
            foreach (SearchField field in this._SearchFields.Values)
            {
                if (field._name.ToLower() == fieldname.ToLower())
                    return field._description;
            }
            return fieldname;
        }

        private void dgTaskList_ItemDataBound(object source, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {

            try
            {
                if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
                {
                    string url = string.Empty;
                    if (this._SearchType != "AP")
                    {
                        string appid = e.Item.Cells[0].Text;
                        string flowid = e.Item.Cells[1].Text;

                        url = string.Format("../workflow/WorkflowView.aspx?appid={0}&flowid={1}&PDType={2}&State=View&Type=App", appid, flowid, this._SearchType);

                    }
                    else
                    {
                        string apid = e.Item.Cells[0].Text;
                        string meetingid = e.Item.Cells[1].Text;

                        url = string.Format("../UserControls/EV/ActionPoint.aspx?APID={0}&MeetingID={1}&Status=Readonly", apid, meetingid);

                    }

                    ImageButton iblegal = (ImageButton)e.Item.FindControl("imageAdvancedSearch");

                    iblegal.Attributes.Add("onclick", "javascript:showView('" + url + "');");

                }
            }
            catch (GDCException gdcEx)
            {
                WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
            }
            catch (Exception ex)
            {
                WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
            }
        }
        #region SearchField
        [Serializable]
        private class SearchField
        {
            public string _name = string.Empty;
            public string _description = string.Empty;
            public bool _isdefault = false;
            public bool _issearch = false;
            public string _datatype = "Str";
            public SearchField()
            {
            }
            public SearchField(string name, string description, bool isdefault, bool issearch, string datatype)
            {
                _name = name;
                _description = description;
                _isdefault = isdefault;
                _issearch = issearch;
                _datatype = datatype;
            }
        }
        #endregion

    }
}
